<template>
  <div ref="refSlotContainer">
    <slot v-if="show || !destroyOnReset" :width="dWidth" :height="dHeight" />
  </div>
</template>

<script>
import {debounce} from 'lodash'
export default {
  name: "DynamicRectContainer",
  props: {
    autoReset: {
      type: Boolean,
      default: true
    },
    destroyOnReset: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: true,
      dWidth: 0,
      dHeight: 0,
      // 每个组件示例new一个防抖的计算边界方法
      debounceResetBounding: null
    }
  },
  watch: {
    autoReset(val) {
      if (val) {window.addEventListener('resize', this.debounceResetBounding)}
      else {window.removeEventListener('resize', this.debounceResetBounding)}
    }
  },
  created() {
    this.debounceResetBounding = debounce(this.resetBounding, 500)
    if (this.autoReset) {window.addEventListener('resize', this.debounceResetBounding)}
  },
  mounted() {
    this.debounceResetBounding()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.debounceResetBounding)
  },
  methods: {
    resetBounding() {
      this.show = false
      this.$nextTick(() => {
        const {height, width} = this.$refs.refSlotContainer.getBoundingClientRect()
        this.dWidth = width
        this.dHeight = height
        this.show = true
      })
    }
  }
}
</script>

<style scoped>

</style>
